package dbBean;

import java.sql.*;
import java.util.*;


public class DBConnPool {
	
	private int inUse=0;
	
	private Vector connections = new Vector();
	
	private String poolname;
	
	private String dbid;
	
	private String drivername;
	
	private String username;
	
	private String passwd;
	
	private int maxconn;

	public DBConnPool(String poolname, String drivername, String dbid, String username, String passwd, int maxconn) {
		this.poolname = poolname;
		this.dbid = dbid;
		this.drivername = drivername;
		this.username = username;
		this.passwd = passwd;
		this.maxconn = maxconn;
	}

	
	public synchronized void releaseConnection(Connection con) {
		
		connections.addElement(con);
		
		inUse--;
	}

	
	public synchronized Connection getConnection() {
		Connection con = null;
		if (connections.size() > 0) {
			
			con = (Connection) connections.elementAt(0);
			connections.removeElementAt(0);
			
         try {
            if (con.isClosed())
               con = getConnection();
         }
         catch (Exception ex) {
            ex.printStackTrace();
         }
		}
		
		else if (maxconn == 0 || inUse < maxconn) {
			con = newConnection();
		}
		if (con != null) {
			inUse++;
		}
		
		return con;
	}

	
	private Connection newConnection() {
		Connection con = null;
		try {
			
			Class.forName(drivername);
			
			con = DriverManager.getConnection(dbid, username, passwd);
		}
		catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
		return con;
	}

	
	public synchronized void closeConn() {
		Enumeration allConnections = connections.elements();
		while (allConnections.hasMoreElements()) {
			Connection con = (Connection) allConnections.nextElement();
			try {
				con.close();
			}
			catch (SQLException e) {
				e.printStackTrace();
			}
		}
		connections.removeAllElements();
	}
}
